import base64
from django import template
from django.utils.safestring import mark_safe

register = template.Library()

@register.filter

def base64_encode(value):
    """将二进制数据转换为base64编码字符串"""
    if value:
        return mark_safe(base64.b64encode(value).decode('utf-8'))
    return ''

@register.filter(name='add_class')
def add_class(field, css_class):
    return field.as_widget(attrs={'class': css_class})

@register.filter

def split(value, delimiter):
    """Split a string by the given delimiter and return a list"""
    if value:
        return value.split(delimiter)
    return []

@register.filter

def get_item(dictionary, key):
    """Get an item from a dictionary by key"""
    if dictionary and key in dictionary:
        return dictionary[key]
    return None

@register.filter

def values(queryset, field_name):
    """Extract values from a queryset or list of dictionaries for a given field name"""
    if hasattr(queryset, 'values_list'):
        # If it's a Django queryset
        return list(queryset.values_list(field_name, flat=True))
    elif isinstance(queryset, list):
        # If it's a list of dictionaries or objects
        result = []
        for item in queryset:
            if isinstance(item, dict) and field_name in item:
                result.append(item[field_name])
            elif hasattr(item, field_name):
                # Handle nested fields like 'homework__content'
                value = item
                for part in field_name.split('__'):
                    if hasattr(value, part):
                        value = getattr(value, part)
                    else:
                        value = None
                        break
                result.append(value)
        return result
    return []